<script setup lang="ts">
import router from '@/router'
import { addPatientApi, deletePatientApi, editPatientApi, getPatientListApi } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { Patient } from '@/types/user'
import { idCardRule, nameRule } from '@/utils/rules'
import { showConfirmDialog, showToast, type FormInstance } from 'vant'
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

// 获取患者列表
const patientList = ref<Patient[]>([])
const getList = async () => {
  const res = await getPatientListApi()
  patientList.value = res.data

  const defaultPatient = patientList.value.find((item) => item.defaultFlag === 1)
  if (defaultPatient) {
    // 有默认值，选中默认  知识点：空值合并运算符??,只对null、undefined生效，如果为null，则赋予后面的值
    isSelectedId.value = defaultPatient?.id ?? ''
  } else {
    // 没有默认值，选中第一个
    isSelectedId.value = patientList.value[0].id ?? ''
  }
}
onMounted(() => {
  getList()
})

// 展示popup
const showPopup = ref(false)
const propupShow = (item?: Patient) => {
  // 如果传了item，说明是编辑患者，回显一下信息
  if (item) {
    // 知识点【对象解构赋值经验】：记住这种使用方式
    const { name, id, gender, idCard, defaultFlag } = item
    patientForm.value = { name, id, gender, idCard, defaultFlag }
  }

  showPopup.value = true
}

//性别选项
const items = [
  { label: '男', value: 1 },
  { label: '女', value: 0 },
]

// 关闭弹出层
const propupClose = () => {
  showPopup.value = false
  // 清空、初始化表单
  patientForm.value = { ...patient }
  addForm.value?.resetValidation()
}

// 新增患者
// 单独定义一个对象出来，是为了方便复用
const patient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0,
}
const patientForm = ref<Patient>({ ...patient })
// 计算默认就诊人（vant的checkbox组件收集的数据是boolean类型，我们要转为数字）
const defaultFlagComputed = computed({
  get: () => (patientForm.value.defaultFlag === 1 ? true : false),
  set: (val: boolean) => {
    patientForm.value.defaultFlag = val ? 1 : 0
  },
})
// 提交数据
const addForm = ref<FormInstance>()
const submitPatient = async () => {
  await addForm.value?.validate()
  if (+patientForm.value.idCard.slice(-2, -1) % 2 !== patientForm.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '身份证号的性别与当前选择性别不符\n是否确认添加？',
    })
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
  patientForm.value.id
    ? await editPatientApi(patientForm.value)
    : await addPatientApi(patientForm.value)

  showToast(patientForm.value.id ? '编辑成功' : '添加成功')
  propupClose()
  getList()
}

// 删除患者
const removePatient = async () => {
  await showConfirmDialog({
    title: '温馨提示',
    message: '是否确认删除该患者？',
  })
  // 知识点【Ts的类型】：因为id属性是非必填，它可能是undefined，所以这里要做一个判断，不然TS会提示错误
  if (patientForm.value.id) {
    await deletePatientApi(patientForm.value.id)
    showToast('删除成功')
    propupClose()
    getList()
  }
}

//判断展示家庭档案、添加患者页面
const route = useRoute()
const isChange = ref()
onMounted(() => {
  isChange.value = route.query.isChange
})

//选中患者
const isSelectedId = ref('')
const onSelected = (id: string) => {
  isSelectedId.value = id
}
// 提交表单
const store = useConsultStore()
const onSubmit = () => {
  store.setPatientId(isSelectedId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"> </cp-nav-bar>
    <!-- 头部选择提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        :class="isSelectedId === item.id ? 'selected' : ''"
        @click="onSelected(item.id as string)"
        v-for="item in patientList"
        :key="item.id"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{
            item.idCard.replace(/^(\d{6})(\d{8})(\d{3}[\dXx])$/, '$1********$3')
          }}</span>
          <span>{{ item.gender === 1 ? '男' : '女' }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon"><svg-icon name="user-edit" @click="propupShow(item)" /></div>
        <div v-show="item.defaultFlag === 1" class="tag">默认</div>
      </div>

      <div v-if="patientList.length <= 10" class="patient-add" @click="propupShow()">
        <svg-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
      <!-- 患者选择下一步 -->
      <div class="patient-next" v-if="isChange">
        <van-button type="primary" @click="onSubmit" round block>下一步</van-button>
      </div>
    </div>
    <!-- 添加患者弹出层 -->
    <van-popup v-model:show="showPopup" position="right">
      <cp-nav-bar
        :title="patientForm.id ? '编辑患者' : '添加患者'"
        rightText="保存"
        :popupBack="propupClose"
        @click-right="submitPatient"
      ></cp-nav-bar>
      <!-- 表单 -->
      <van-form class="patient-form" autocomplete="off" ref="addForm">
        <van-field
          label="真实姓名"
          :rules="nameRule"
          v-model="patientForm.name"
          placeholder="请输入真实姓名"
        />
        <van-field
          label="身份证号"
          :rules="idCardRule"
          v-model="patientForm.idCard"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn v-model="patientForm.gender" :items="items"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlagComputed" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="patientForm.id">
        <van-action-bar-button text="删除患者" @click="removePatient" />
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;

  .van-popup--right {
    width: 100%;
    height: 100%;

    .patient-form {
      margin-top: 46px;
    }
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-tip {
  padding: 0;
}
.patient-next {
  padding: 15px;
  // background-color: #fff;
  background-color: transparent; //背景透明

  position: fixed;
  left: 0;
  bottom: 30px;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
</style>
